import * as esbuild from 'esbuild-wasm';

export const unpkgPathPlugin =() => {
    return {
        name: 'unpkg-path-plugin',
        setup(build: esbuild.PluginBuild) {
            // Handle 入口文件
            build.onResolve({ filter: /(^index\.js$)/ }, () => {
                return { path: 'index.js', namespace: 'a'};
            })
            // Handle 文件里的相对路径 ./file 和 ../file
            build.onResolve({ filter: /^\.+\//}, async (args: any) => {
                if (args.path.includes('./') || args.path.includes('../')) {
                    return { namespace: 'a', path: new URL(args.path, `https://unpkg.com${args.resolveDir}/`).href
                    }
                }
            })
            // Handle 主模块文件
            build.onResolve({ filter: /.*/}, async (args: any) => {
                return {
                    namespace: 'a',
                    path: `https://unpkg.com/${args.path}`
                }
            });

        }
    }
}
